package businessDelegate;

import interfaces.InterfaceRemota;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import javax.naming.CommunicationException;
import javax.swing.JOptionPane;

import dto.UbicacionDTO;

public class Delegate {

	private static Delegate instancia;
	private InterfaceRemota referenciaRemota;

	private Delegate () throws CommunicationException, RemoteException, NotBoundException
	{
		conexionRemota();
	}
	
	private void conexionRemota() throws CommunicationException, RemoteException, NotBoundException
	{
		try 
		{
			final String IP = "127.0.0.1";
		    final Registry registry = LocateRegistry.getRegistry(IP, Registry.REGISTRY_PORT);
		    final String[] enlacesRemotos = registry.list();
		    
		    for (String enlace : enlacesRemotos) 
		    {
		    	referenciaRemota = (InterfaceRemota) Naming.lookup(enlace);
		    }
			
		} catch (MalformedURLException e) 
		{
			throw new CommunicationException("Error al establecer la conexion");
		}
	}

	public static Delegate getInstancia() throws CommunicationException, RemoteException, NotBoundException
	{
		if(instancia==null)
			instancia=new Delegate();
		return instancia;
	}
	
	public void testUbicacion(UbicacionDTO ubicacion)
	{
		try 
		{
			referenciaRemota.testUbicacion(ubicacion);
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, e.getMessage());
		}
		return;
		
	}

}
